#include <iostream>
#include <signal.h>
#include <string>

#include "../comm/httplib.h"
#include "oj_control.hpp"
#include "login_and_register.hpp"

using namespace httplib;
using namespace ns_control;
using namespace ns_login_register;
using namespace ns_util;
static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT, Recovery);
    Server svr;
   
    Control ctrl;
    ctrl_ptr = &ctrl;
    Register rg;
    // //Debug
    // std::cout << "debug3"<<std::endl;
    //获取所有的题目列表
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp){
        // //Debug
        // std::cout << "debug2"<<std::endl;
        std::string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html; charset=utf-8");
    });
    // //Debug
    // std::cout << "debug4"<<std::endl;

    // http://43.138.112.14:8080/question/1
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp){
        // //Debug
        // std::cout << "debug5"<<std::endl;
        std::string html;
        std::string number = req.matches[1]; // 用于提取正则表达式中的第一个分组，matches[0]是提取全部
        ctrl.OneQuestion(number, &html);
        resp.set_content(html, "text/html; charset=utf-8");
    });

    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp){
        std::string number = req.matches[1];
        std::string result_json;
        ctrl.Judge(number, req.body, &result_json);
        resp.set_content(result_json, "application/json;charset=utf-8");
    });

    svr.Get("/login", [](const Request &req, Response &resp){
        std::string result_json;
        std::string login_path = "./login_register_html/login.html";
        std::string content;
        FileUtil::ReadFile(login_path, &content);
        
        //lg.Login(req.body, &result_json);
        resp.set_content(content, "text/html;charset=utf-8");
    });
    
    svr.Get("/register", [](const Request &req, Response &resp){
        std::string result_json;
        std::string login_path = "./login_register_html/register.html";
        std::string content;
        FileUtil::ReadFile(login_path, &content);
        
        //lg.Login(req.body, &result_json);
        resp.set_content(content, "text/html;charset=utf-8");
    });

    svr.Post("/get_username", [&rg](const Request &req, Response &resp){
        
        std::string out_json;
        rg.getUsername(&out_json);
        LOG(DEBUG) << "out_json: " << out_json << std::endl;
        resp.set_content(out_json, "application/json;charset=utf-8");
    });

    svr.Post("/register_judge", [&rg](const Request &req, Response &resp){
        std::string result_json = req.body;
        rg.register1(result_json);
        resp.set_content(result_json, "application/json;charset=utf-8");
    });



    svr.set_base_dir("./wwwroot");
    svr.listen("0.0.0.0",8080);
    return 0;
}